package com.badibadi.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.badibadi.infos.Record_Info_Model;
import com.badibadi.infos.Results;
import com.badibadi.mytools.Constants;
import com.badibadi.mytools.JSONUtils;
import com.badibadi.mytools.MyThreadTool;
import com.badibadi.mytools.Utils;
import com.badibadi.uniclubber.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

//修改记录
public class EditTheRecordActivity extends AddingRecordNewActivity {// group_toupiao
																	// record_new_radio0
	private Results results;
	private Record_Info_Model info_Model_1;
	// private TextView AddingRecord_New_text0;// 篇的名字
	// private ImageView record_new_img;// 篇的背景
	// private Spinner record_new_quanxian;// 篇的权限
	// private RadioGroup group_toupiao;// 是否投票
	// private RadioButton radio0, radio1;
	private DisplayImageOptions options;
	private String[] QQxian;
	protected static final String TAG = "EditTheRecordActivity";
	private ArrayAdapter<String> adapter;
	private List<String> allCountries;
	// private GridView adding_record_new_label_type_gridView1;// 标签
	String rid, cid;// 如果是个人cid为null;
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				Utils.ExitPrgress(EditTheRecordActivity.this);
				Utils.showMessage(EditTheRecordActivity.this, getResources()
						.getString(R.string.l_net_error));
				break;
			case 2:
				Utils.ExitPrgress(EditTheRecordActivity.this);
				AddData();
				break;
			case 3:
				Utils.ExitPrgress(EditTheRecordActivity.this);
				Utils.showMessage(EditTheRecordActivity.this, getResources()
						.getString(R.string.l_xa10));
				break;
			case 4:
				Utils.ExitPrgress(EditTheRecordActivity.this);
				Utils.showMessage(EditTheRecordActivity.this, getResources()
						.getString(R.string.l_xb55));
				Constants.is_shuaxin = true;
				EditTheRecordActivity.this.finish();
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		rid = getIntent().getStringExtra("rid");
		cid = getIntent().getStringExtra("cid");
		if (cid != null) {
			if (cid.equals("0")) {
				cid = null;
			}
		}
		init();
	}

	private void init() {
		Constants.is_shuaxin = false;
		QQxian = new String[] { getResources().getString(R.string.l_xb30),
				getResources().getString(R.string.AllThePeople) };

		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.ic_stub)
				.showImageForEmptyUri(R.drawable.noimage)
				.showImageOnFail(R.drawable.noimage).cacheInMemory()
				.cacheOnDisc().displayer(new RoundedBitmapDisplayer(5)).build();
		this.findViewById(R.id.record_istoupian).setVisibility(View.VISIBLE);
		TextView tv = (TextView) this.findViewById(R.id.title);
		tv.setText(R.string.AmendantRecord);
		this.findViewById(R.id.rl_addNew).setVisibility(View.GONE);
		this.findViewById(R.id.record_new_uppic_settings).setOnClickListener(
				new OnClickListener() {
					@Override
					public void onClick(View arg0) {
						TitleMap = getArnAdapter().getTitleMap();
						Size = getArnAdapter().getMapSize();
						//    
						TiJiao();
						if (getBeginFirstRecord().getName() != null) {
							if (!getBeginFirstRecord().getMap().isEmpty()) {
								if (getBeginFirstRecord().getIsTouPiao() != null
										&& getBeginFirstRecord().getPic() != null
										&& getBeginFirstRecord().getQuanxian() != null) {
									try {
										JSONObject jsonObject = fengzhuang_xiugai(
												null,
												null,
												getBeginFirstRecord().getName(),
												getBeginFirstRecord().getPic(),
												getBeginFirstRecord()
														.getQuanxian(), null,
												getBeginFirstRecord()
														.getIsTouPiao(), rid);
										revise_record(jsonObject);
									} catch (JSONException e) {
										// TODO Auto-generated catch block
										   
									}
								} else {
									Toast.makeText(
											getApplicationContext(),
											getResources().getString(
													R.string.l_xb26), 0).show();
								}
							} else {
								Toast.makeText(
										getApplicationContext(),
										getResources().getString(
												R.string.l_xb32), 0).show();
							}
						} else {
							Toast.makeText(getApplicationContext(),
									getResources().getString(R.string.l_xb33),
									0).show();
						}
					}
				});

	}

	@Override
	protected void initGridView() {
		// TODO Auto-generated method stub
		super.initGridView();
		record_info(rid);
	}

	public void add() {
		// TODO Auto-generated method stub
//		   
		try {
			String[] id_1 = back_biaoqian(info_Model_1.getType_id());
//			   (id_1.length);
			for (int i = 0; i < id_1.length; i++) {
				//    (id_1[i]);
				// getArnAdapter().setIsItemClick_id(
				// id_1[i].substring(1, id_1[i].length()));
				getArnAdapter().setIsItemClick_id(id_1[i]);
			}
			getArnAdapter().notifyDataSetInvalidated();
		} catch (Exception e) {
			   
		}
		//    ("运行");
	}

	private void AddData() {
		add();
		// AddingRecord_New_text0 = (TextView)
		// findViewById(R.id.AddingRecord_New_text0);
		// record_new_img = (ImageView) findViewById(R.id.record_new_img);
		// record_new_quanxian = (Spinner)
		// findViewById(R.id.record_new_quanxian);
		// group_toupiao = (RadioGroup) findViewById(R.id.group_toupiao);
		// radio0 = (RadioButton) findViewById(R.id.record_new_radio0);
		// radio1 = (RadioButton) findViewById(R.id.record_new_radio1);
		// adding_record_new_label_type_gridView1 = (GridView)
		// findViewById(R.id.adding_record_new_label_type_gridView1);
		getBeginFirstRecord().setQuanxian(info_Model_1.getP_status());
		getBeginFirstRecord().setIsTouPiao(info_Model_1.getIs_vote());
		getBeginFirstRecord().setPic(info_Model_1.getImage());
		getBeginFirstRecord().setName(info_Model_1.getNickName());
		// getBeginFirstRecord().setMap(map)
		et0.setText(info_Model_1.getTitle());
		// asdf
		ImageLoader.getInstance().displayImage(
				Constants.BadiDownImgUrl + info_Model_1.getImage()
						+ Constants.appPhoto4img, iv_image, options);
		if (cid != null) {
			allCountries = new ArrayList<String>();
			for (int i = 0; i < QQxian.length; i++) {
				allCountries.add(QQxian[i]);
			}
			adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, allCountries);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			quanxian.setAdapter(adapter);
			switch (Integer.valueOf(info_Model_1.getC_status())) {
			case 0:
				quanxian.setSelection(0);
				break;
			case 1:
				quanxian.setSelection(1);
				break;
			default:
				quanxian.setSelection(0);
				break;
			}
		} else {
			switch (Integer.valueOf(info_Model_1.getP_status())) {
			case 0:
				quanxian.setSelection(0);
				break;
			case 1:
				quanxian.setSelection(1);
				break;
			case 2:
				quanxian.setSelection(2);
				break;
			default:
				quanxian.setSelection(0);
				break;
			}
		}

		if (info_Model_1.getIs_vote().equals("1")) {
			radio0.setChecked(true);
			radio1.setChecked(false);
		} else {
			radio0.setChecked(false);
			radio1.setChecked(true);
		}
	}

	private String[] back_biaoqian(String dst) {
		String sd[] = dst.split(",");
		return sd;
	}

	private void revise_record(final JSONObject object) {
		Utils.showPrgress(EditTheRecordActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("record", object);
				String content = Utils.sendRequest(map, Constants.BadiUrl
						+ "revise_record");
//				   ("需修改的记录的内容是:" + map.toString());
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
//					   ("记录修改的内容是:" + results.getRetmsg());
					if (results != null && !results.getRetmsg().equals("null")) {
						handler.sendEmptyMessage(4);
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private JSONObject fengzhuang_xiugai(String c_uid, String club_id,
			String title, String image, String p_status, String c_status,
			String is_vote, String rid) throws JSONException {
		String typid = "";
		JSONObject object = new JSONObject();
		object.put("uid", Utils.getUid(EditTheRecordActivity.this));
		if (c_uid != null) {// 俱乐部管理员id（选传）
			object.put("c_uid", c_uid);
		}
		if (club_id != null) {// 俱乐部id（选传）
			object.put("club_id", club_id);
		}
		if (c_status != null) {// 俱乐部记录的权限（选传）
			object.put("c_status", c_status);
		}
		object.put("rid", rid);
		object.put("image", image);
		object.put("p_status", p_status);
		object.put("title", title);
		object.put("is_vote", is_vote);
//		   
		if (getBeginFirstRecord().getMap() != null
				&& !getBeginFirstRecord().getMap().isEmpty()) {

			for (int i = 0; i < Size; i++) {
				if (getBeginFirstRecord().getMap().get(i) != null) {
					typid += getBeginFirstRecord().getMap().get(i) + ",";
				}
			}
//			   
			object.put("type_id", typid.substring(0, typid.length() - 1));
		}
		// object.put("type_id", type_id);
		return object;
	}

	private void record_info(final String rid) {
		// Utils.showPrgress(EditTheRecordActivity.this);
		MyThreadTool.fixedThreadPool.execute(new Runnable() {
			@Override
			public void run() {
				String content = null;
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("rid", rid);
				if (cid != null) {
					content = Utils.sendRequest(map, Constants.BadiUrl_1
							+ "record/editRecordShow");
//					   
				} else {
					content = Utils.getRequest(Constants.BadiUrl
							+ "record_info?rid=" + rid);
//					   
				}
				if (content != null) {
					results = Utils.checkResult_NNN(getApplicationContext(),
							content);
					if (results != null && !results.getRetmsg().equals("null")) {
						//    ("篇的内容是:" + results.getRetmsg());
//						   
						try {
							info_Model_1 = JSONUtils.getEntityByJsonString(
									results.getRetmsg(),
									Record_Info_Model.class);
							handler.sendEmptyMessage(2);
						} catch (Exception e) {
							   
						}
					} else {
						handler.sendEmptyMessage(3);
					}
				} else {
					handler.sendEmptyMessage(1);
				}
			}
		});
	}
}
